<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据导出</title>
    <link rel="stylesheet" href="./css/reset.css" />
    <link rel="stylesheet" href="./css/index.css" />
    <!-- 引入 Element Plus 的 CSS -->
    <link rel="stylesheet" href="./css/element-plus@2.3.10.css">
    <!-- 引入 Vue 3 的 JS -->
    <script src="./js/vue.global.js"></script>
    <!-- 引入 Element Plus 的 JS -->
    <script src="./js/element-plus@2.3.10.full.js"></script>
    <!-- 引入 alova -->
    <script src="./js/alova@2.1.2.umd.min.js"></script>
    <script src="./js/alova@2.1.2.globalfetch.umd.min.js"></script>
    <script src="./js/alova@2.1.2.vuehook.umd.min.js"></script>
    <script src="./js/request.js"></script>
    <script src="./js/api.js"></script>
    <style>
        .custom-radio-group {
            flex-wrap: nowrap;
        }
        .custom-checkbox-group {
            display: flex;
            flex-direction: row; 
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="common-layout">
            <el-container>
                <el-header>LP、政府引导基金排名数据导出</el-header>
                <el-main>
                    <div>
                        <el-form
                            ref="ruleFormRef"
                            style="width: 100%"
                            :model="ruleForm"
                            :rules="rules"
                            label-width="100px"
                        >   
                            <el-form-item label="年份" prop="year">
                                <el-date-picker
                                    v-model="ruleForm.year"
                                    type="year"
                                    aria-label="年份"
                                    placeholder="请选择年份"
                                    style="width: 100%"
                                    disabled
                                />
                            </el-form-item>
                            <el-form-item label="类型" prop="type">
                                <el-checkbox-group v-model="ruleForm.type" class="custom-checkbox-group">
                                    <el-checkbox label="LP" name="type" border>LP</el-checkbox>
                                    <el-checkbox label="GGF" name="type" border>政府引导基金</el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                            <el-form-item label="提交类型" prop="isSubmit">
                                <el-radio-group v-model="ruleForm.isSubmit" class="custom-radio-group">
                                    <el-radio :label='1' border>已提交</el-radio>
                                    <el-radio :label='2' border>未提交</el-radio>
                                    <el-radio :label='3' border>全部</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="是否合并" prop="isMerge">
                                <el-radio-group v-model="ruleForm.isMerge" class="custom-radio-group">
                                    <el-radio :label='1' border>不合并</el-radio>
                                    <el-radio :label='2' border>合并</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="时间范围" required>
                                <el-form-item prop="start">
                                    <el-date-picker
                                        v-model="ruleForm.start"
                                        type="date"
                                        aria-label="开始时间"
                                        placeholder="请选择开始时间"
                                        style="width: 100%"
                                        disabled
                                    />
                                </el-form-item>
                                <span style="margin: 0 20px;">-</span>
                                <el-form-item prop="end">
                                    <el-date-picker
                                        v-model="ruleForm.end"
                                        type="date"
                                        aria-label="结束时间"
                                        placeholder="请选择结束时间"
                                        style="width: 100%"
                                        disabled
                                    />
                                </el-form-item>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="submitForm(ruleFormRef)">
                                    导出数据
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div>
                        <el-table 
                            :data="tableData" 
                            height="350" 
                            stripe 
                            style="width: 100%" 
                            empty-text="暂无数据" 
                            v-loading="loading"
                            element-loading-text="列表数据正在加载中..."
                            :element-loading-spinner="svg"
                            element-loading-svg-view-box="-10, -10, 50, 50"
                            element-loading-background="rgba(122, 122, 122, 0.8)">
                            <el-table-column prop="file_name" label="文件名称" min-width="200" align="center"></el-table-column>
                            <el-table-column fixed="right" label="操作" width="220" align="center">
                                <template #default="scope">
                                  <el-button link type="primary" size="small" @click="handleDownload(scope.row)">
                                    下载
                                  </el-button>
                                  <!-- <el-button link type="primary" size="small">删除</el-button> -->
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-main>
                <el-footer></el-footer>
            </el-container>
          </div>
    </div>
    <script>
        const { createApp, ref, reactive, toRefs, onMounted, onUnmounted, getCurrentInstance } = Vue;
        const { FormInstance, FormRules, ElMessage } = 'element-plus'
        const alovaInstance1 = alova.createAlova({    
            baseURL: 'http://127.0.0.1:5555',
            statesHook: VueHook,
            requestAdapter: GlobalFetch(),
            responded: response => response.json(),
            cacheFor: null, // 关闭全局缓存
        });
        const app = createApp({
            setup() {
                const timestamp = Date.now();
                // 存储响应数据
                const loading = ref(false);
                const ruleFormRef = ref()
                const ruleForm = ref({
                    year: '2025',
                    start: '2024-04-01',
                    end: '2025-03-31',
                    type: ['LP'],
                    isMerge: 1,
                    isSubmit: 1,
                })
                const rules = ref({
                    year: [{required: true, message: '请选择年份',trigger: 'change', },],
                    start: [{type: 'date', required: true, message: '请选择开始时间', trigger: 'change', },],
                    end: [{type: 'date', required: true, message: '请选择结束时间', trigger: 'change',},],
                    type: [{type: 'array', required: true, message: '请选择类型', trigger: 'change',},],
                    isMerge: [{required: true, message: '请选择是否合并', trigger: 'change',},],
                    isSubmit: [{required: true, message: '请选择提交类型', trigger: 'change',},],
                })
                const svg = `
                    <path class="path" d="
                    M 30 15
                    L 28 17
                    M 25.61 25.61
                    A 15 15, 0, 0, 1, 15 30
                    A 15 15, 0, 1, 1, 27.99 7.5
                    L 15 15
                    " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
                `
                // 设定10秒调用一次接口，刷新列表数据
                const tableData = ref([]);
                const countdown = ref(10); // 倒计时秒数
                let intervalId = ref(null);
                // 清理定时器
                onMounted(() => LpGgfApi.getList())
                onUnmounted(() => clearInterval(intervalId.value));
                const startPolling = () => {
                    intervalId.value = setInterval(() => {
                        if (countdown.value > 0) {
                            countdown.value--;
                        } else {
                            fetchData(); // 调用接口
                            countdown.value = 10; // 重置倒计时
                        }
                    }, 1000);
                };
                const fetchData = () => {
                    loading.value = true;
                    let ret = alovaInstance.Get('/getList?_=' + `${timestamp}`)
                    .send(true)
                    .then((result) => {
                        result ? tableData.value = result.data : tableData.value = [];
                        console.log('result----', result);
                    }).catch((err) => {
                        clearInterval(intervalId.value);
                    }).finally(() => {  
                        loading.value = false;
                    });
                    console.log('ret----', ret);
                    console.log('loading---', loading.value);
                }
                // 启动轮询
                startPolling();
                // 下载
                const download = async (row) => {
                    if (row.file_name) {
                        console.log('row----', row);
                        
                        await alovaInstance.Get('/download?_=' + `${timestamp}&file_name=` + row.file_name,
                            {
                                responseType: 'blob',
                                headers: { Accept: 'application/octet-stream' }
                            }
                        );
                    }
                }
                const { send } = alova.useRequest(download, { immediate: false });
                const handleDownload = async (row) => {
                    const response = await send(row);
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    
                    // 解析文件名（优先从响应头获取）
                    const contentDisposition = response.headers.get('Content-Disposition');
                    const filename = contentDisposition?.split('filename=')[1] || 'default.pdf';
                    
                    // 创建隐藏链接触发下载
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = decodeURIComponent(filename);
                    a.click();
                    window.URL.revokeObjectURL(url);
                };
                const submitForm = async () => {
                    try {
                        await ruleFormRef.value.validate();
                        console.log("表单数据：", ruleForm); 
                        const { loading, error, data } = alova.useRequest(
                            await alovaInstance.Post('/export?_=' + `${timestamp}`, ruleForm.value,
                                {
                                    headers: {
                                        'Content-Type': 'application/json;charset=utf-8'
                                    }
                                }
                            )
                        );
                        ElementPlus.ElMessage({
                            message: '数据正在导出，请稍候到列表下载！',
                            type: 'success',
                            plain: true,
                            showClose: true,
                        })
                        console.log("loading：", loading);
                        console.log("error：", error);
                        console.log("data：", data);
                    } catch (error) {
                        console.log("验证失败：", error);
                    }
                };
                return {
                    fetchData,
                    loading,
                    ruleForm,
                    submitForm,
                    rules,
                    ruleFormRef,
                    tableData,
                    svg,
                    handleDownload,
                };
            }
        });
        // 使用 Element Plus
        app.use(ElementPlus);
        // 挂载应用
        app.mount('#app');
    </script>
</body>
</html>